#--
# Active Directory Module for Ruby
#
# Copyright (c) 2005-2006 Justin Mecham
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#++

module ActiveDirectory
  #
  # Represents a Group object within an Active Directory instance.
  #
  class Group < Base
    extend Schema::Group

    def has_member?(user)
      user.member_of?(self)
    end
    
    def add_to_group(user)
      append_to_multivalue_attribute(:member,user.dn)
    end

    def remove_from_group(user)
      return unless user.member_of? self
      remove_from_multivalue_attribute(:member, user.dn)
    end

    def members(recursive = true)
      list = []
      member.each do |member_dn|
        begin
          list << User.find(member_dn)
        rescue NotFoundError => e
          if recursive
            # Member was not a User.  try to find a Group
            begin
              subgroup = Group.find(member_dn)
              list += subgroup.members
            rescue NotFoundError => e
              next
            end
          end
        end
      end
      list.uniq
    end

    def groups
      list = []
      member.each do |group_dn|
        begin
          list << Group.find(group_dn)
        rescue NotFoundError => e
          next
        end
      end
      list
    end
  end
end
